{extend name="../../../view/public/base" /}

{block name="body"}
<div class="bw-container">
    <div class="bw-main">
        <div class="layui-row layui-col-space15">

            <div class="layui-col-md12">
                <div class="layui-card">
                    <div class="layui-collapse" lay-filter="test">
                        <div class="layui-colla-item">
                            <h2 class="layui-colla-title"><i class="layui-icon">&#xe615;</i>查询条件</h2>
                            <div class="layui-colla-content">
                                <br>
                                <div class="demoTable layui-form ">
                                    <div class="layui-inline">
                                        <label class="layui-form-label">分类ID：</label>
                                        <div class="layui-inline">
                                            <input class="layui-input" name="id" id="id" autocomplete="off" placeholder="配置分类ID">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label">分类名称：</label>
                                        <div class="layui-inline">
                                            <input class="layui-input" name="title" id="title" autocomplete="off" placeholder="配置分类名称">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label">分类标识：</label>
                                        <div class="layui-inline">
                                            <input class="layui-input" name="tab_name" id="tab_name" autocomplete="off" placeholder="配置分类标识">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label">查询应用：</label>
                                        <div class="layui-input-inline">
                                            <select name="dir" id="miniapp_name" lay-filter="miniapp_name">
                                                <option value="">请选择</option>
                                                {volist name="miniapp" id="vo" key="k"}
                                                <option value="{$vo.dir}">{$vo.title}</option>
                                                {/volist}
                                            </select>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label">查询插件：</label>
                                        <div class="layui-input-inline">
                                            <select name="dir" id="plugin_name" lay-filter="plugin_name">
                                                <option value="">请选择</option>
                                                {volist name="plugin" id="vo" key="k"}
                                                <option value="{$vo.name}">{$vo.title}</option>
                                                {/volist}
                                            </select>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <label class="layui-form-label">配置范围：</label>
                                        <div class="layui-input-inline">
                                            <select name="scopes" id="scopes" lay-verify="required">
                                                <option value="">请选择</option>
                                                <option value="common">平台</option>
                                                <!--<option value="admin">管理员</option>-->
                                                <option value="member">租户</option>
                                            </select>
                                        </div>
                                    </div>
                                    <br><br>
                                    <div class="layui-inline">
                                        <label class="layui-form-label">是否显示：</label>
                                        <div class="layui-input-inline">
                                            <select name="is_show" id="is_show" lay-verify="required">
                                                <option value="">请选择</option>
                                                <option value="1">显示</option>
                                                <option value="0">隐藏</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <div class="layui-input-inline">
                                            &nbsp&nbsp&nbsp
                                            <button class="layui-btn layui-btn-sm   layui-btn-warm" onclick="reload()">搜索</button>
                                            <button class="layui-btn layui-btn-sm" onclick="reset()">重置</button>
                                        </div>
                                    </div>
                                    <br><br>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-col-md12">
                <div class="layui-card">
                    <div class="layui-tab layui-tab-brief" lay-filter="docDemoTabBrief">
                        <ul class="layui-tab-title ">
                            <li class="layui-this">全部</li>
                            <li>系统配置</li>
                            <li>插件配置</li>
                            <!--<li>应用配置</li>-->
                            <!--<li>其他配置</li>-->
                        </ul>
                    </div>
                </div>
            </div>

            <div class="layui-col-md12">
                <div class="layui-card">
                    <!-- 列表上面按钮 -->
                    <script type="text/html" id="toolbarDemo">
                        <div class="layui-btn-container tbtn">
                            <button class="layui-btn layui-btn-danger layui-btn-sm" type="button" onclick="del('all')"><i class="layui-icon">&#xe640;</i>批量删除分类</button>

                            <button class="layui-btn layui-btn-sm  layui-btn-normal" onclick="edit('','all')">添加配置分类</button>
                            <button class="layui-btn layui-btn-sm  layui-btn-normal" onclick="addconfig('','all')">添加配置</button>
                            <button class="layui-btn layui-btn-sm" onclick="reset()">重置</button>
                            <!--            <button class="layui-btn layui-btn-sm" type="button" onclick="edit('','all','','')"><i class="layui-icon">&#xe654;</i>新增</button>-->
                            <!--        <button class="layui-btn layui-btn-primary layui-btn-sm" type="button" onclick="del('all')"><i class="layui-icon">&#xe640;</i>新增</button>-->

                        </div>
                    </script>
                    <!-- 列表 -->
                    <table class="layui-table" lay-data="{toolbar:'#toolbarDemo',url:'{:Url('getlist?return_type=old_json')}',method:'get',page:true,id:'templateList'}" lay-filter="templateList">
                        <thead>
                        <tr>
                            <th lay-data="{type:'checkbox',fixed: 'left'}"></th>
                            <th lay-data="{field:'id', sort: true}">ID</th>
                            <th lay-data="{field:'sort', sort: true, edit: 'text'}">权重(可编辑)</th>
                            <th lay-data="{field:'title', sort: true}">配置分类名称</th>
                            <th lay-data="{field:'tab_name', sort: true}">配置分类标识</th>
                            <th lay-data="{field:'is_show', templet: '#status2' }">是否显示</th>
                            <th lay-data="{field:'type', templet: '#type' }">配置类型</th>
                            <th lay-data="{field:'app_name', templet: '#app_name' }">所属应用</th>
                            <th lay-data="{field:'plugin_name', templet: '#plugin_title' }">所属插件</th>
                            <th lay-data="{field:'scopes', templet: '#scope' }">配置范围</th>
                            <th lay-data="{fixed: 'right', width:300,  align:'center', toolbar: '#barDemo'}">操作</th>
                        </tr>
                        </thead>
                    </table>
                    <script type="text/html" id="scope">
                        {{#  if(d.scopes == 'common'){ }}<span style="color: #FFB800;">平台</span>{{#  } }}
                        {{#  if(d.scopes == 'admin'){ }}<span style="color: #FF5722;">管理员</span>{{#  } }}
                        {{#  if(d.scopes == 'member'){ }}<span style="color: #1E9FFF;">租户</span>{{#  } }}
                    </script>
                    <script type="text/html" id="app_name">
                        {{#  if(!d.miniapp_name){ }}
                        <span class="layui-badge layui-bg-gray">无</span>
                        {{#  } else { }}
                        <span class="layui-badge layui-bg-blue"> {{d.miniapp_name}}</span>
                        {{#  } }}
                    </script>
                    <script type="text/html" id="plugin_title">
                        {{#  if(!d.plugin_name){ }}
                        <span class="layui-badge layui-bg-gray">无</span>
                        {{#  } else { }}
                        <span class="layui-badge layui-bg-blue"> {{d.plugin_name}}</span>
                        {{#  } }}
                    </script>
                    <script type="text/html" id="type">
                        {{#  if(d.type == '1'){ }}<span style="color: #FFB800;">系统配置</span>{{#  } }}
                        {{#  if(d.type == '2'){ }}<span style="color: #FF5722;">插件配置</span>{{#  } }}
                        {{#  if(d.type == '3'){ }}<span style="color: #1E9FFF;">应用配置</span>{{#  } }}
                        {{#  if(d.type == '4'){ }}<span style="color: #5FB878;">其他配置</span>{{#  } }}
                        {{#  if(d.type == '5'){ }}<span style="color: #5FB878;">应用插件配置</span>{{#  } }}
                    </script>
                    <script type="text/html" id="status2">
                        <input type="checkbox" id="status" name="status" value="{{d.id}}" templateType="{{d.is_show}}" lay-skin="switch" lay-text="显示|隐藏" lay-filter="state" {{ d.is_show== 1 ? 'checked' : '' }}>
                    </script>
                    <script type="text/html" id="barDemo">

                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="edit" title="编辑">编辑</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="addconfig" title="添加配置">添加配置</a>
                        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="list" title="配置列表">查看配置列表</a>
                        <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="del" title="删除">删除</a>
                    </script>

                </div>
            </div>
        </div>
    </div>
</div>
<script>
    var table;
    var laydate;
    var result = "";
    var form;
    var auth_status = '';
    var dtree;
    layui.use(['form', 'table', 'laydate', 'element'], function () {
        var element = layui.element;
        table = layui.table;
        form = layui.form;
        laydate = layui.laydate;
        reset()
        //监听工具条
        table.on('tool(templateList)', function (obj) {
            var data = obj.data;
            if (obj.event === 'del') {
                del(data.id,data.dir);
            } else if (obj.event === 'edit') {
                edit(data.title, data.id,data.dir);
            } else if (obj.event === 'list') {
                list(data.tab_name, data.scopes, data.dir, data.id);
            } else if (obj.event === 'addconfig') {
                addconfig(data.title, 'all', data.id,data.dir);
            }

        });

        //监听单元格编辑
        table.on('edit(templateList)', function (obj) {
            var value = obj.value //得到修改后的值
                , data = obj.data //得到所在行所有键值
                , field = obj.field; //得到字段
            $.ajax({
                url: "{:Url('setshow')}",
                type: "post",
                data: {id: data.id, sort: value, app: data.dir},
                async: false,
                success: function (data) {
                    if (data.data.errcode != 0) {
                        layer.msg('操作失败！请联系管理员或稍后再试。', {
                            icon: 5,
                            time: 1000
                        });
                    } else {
                        layer.msg('更新成功', {
                            icon: 6,
                            time: 1500
                        });
                    }
                }
            });

        });

        //触发tab事件
        element.on('tab(docDemoTabBrief)', function (elem) {
            // location.hash = 'test='+ $(this).attr('lay-id');

            switch (elem.index) {
                case 0:
                    //全部
                    auth_status = '';
                    reload();
                    break;
                case 1:
                    //未审核
                    auth_status = '1';
                    reload();
                    break;
                case 2:
                    //已通过
                    auth_status = '2';
                    reload();
                    break;
                case 3:
                    //审核失败
                    auth_status = '3';
                    reload();
                    break;
                case 4:
                    //审核失败
                    auth_status = '4';
                    reload();
                    break;
            }
        });

        //日期范围
        var begin = laydate.render({
            elem: '#beginTime',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm',
            btns: ['clear', 'confirm'],
            done: function (value, date) {
                if (date.year) {
                    end.config.min = {
                        year: date.year,
                        month: date.month - 1,
                        date: date.date,
                        hours: date.hours,
                        minutes: date.minutes,
                        seconds: 0
                    }
                } else {
                    end.config.min = {
                        year: 1970,
                        month: 1,
                        date: 1,
                        hours: 23,
                        minutes: 59,
                        seconds: 59
                    }
                }
            }
        });
        var end = laydate.render({
            elem: '#endTime',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm',
            btns: ['clear', 'confirm'],
            done: function (value, date) {
                if (date.year) {
                    begin.config.max = {
                        year: date.year,
                        month: date.month - 1,
                        date: date.date,
                        hours: date.hours,
                        minutes: date.minutes,
                        seconds: 0
                    }
                } else {
                    begin.config.max = {
                        year: 2099,
                        month: 12,
                        date: 31,
                        hours: 59,
                        minutes: 59,
                        seconds: 59
                    }
                }
            }
        });

        form.render("select");
        form.on('switch(state)', function (obj) {
            tipText = "操作成功";
            var emelment = $('.layui-form-switch');

            if (isClick) {
                isClick = false;
                var templateType = this.getAttribute("templateType");
                setBoxState(this.value, templateType, true);

                if (result.data.errcode != 0) {
                    layer.msg('操作失败！请联系管理员或稍后再试。', {
                        icon: 5,
                        time: 1000
                    });
                } else {
                    layer.msg(tipText, {
                        icon: 6,
                        time: 1500
                    });
                }
                for (var i = 0; i < emelment.length; i++) {
                    $(emelment[i]).addClass('layui-disabled');
                    $(emelment[i]).unbind();
                }
                setTimeout(function () {
                    isClick = true;
                    curr = $('.layui-laypage-em').next().text();
                    reload();
                }, 1500);
            } else {
                layer.msg('请不要操作太频繁！', {
                    icon: 5,
                    time: 1000
                });
            }
        });

    });

    //设置推荐
    function setBoxState(id, templateType, state) {
        var miniapp_name = $('#miniapp_name').val();
        $.ajax({
            url: "{:Url('setshow')}",
            type: "post",
            data: {id: id, state: state, status: templateType,app:miniapp_name},
            async: false,
            success: function (data) {
                result = data;
            }
        });
    }

    //获取所选中的ID
    function getCheckData() {
        var checkStatus = table.checkStatus('templateList'), data = checkStatus.data;
        var obj = [];
        for (var i = 0; data.length > i; i++) {
            obj.push(data[i].id);
        }
        layer.alert(JSON.stringify(obj));
    }

    //获取重载列表
    function reload() {
        // var beginTime = $("#beginTime").val();
        // var endTime = $("#endTime").val();

        var scopes = $('#scopes').val();
        var is_show = $('#is_show').val();
        var title = $('#title').val();
        var id = $('#id').val();
        var tab_name = $('#tab_name').val();
        var miniapp_name = $('#miniapp_name').val();
        var plugin_name = $('#plugin_name').val();
        //var category_id = $('#category_id').val();
        table.reload('templateList', {
            where: { //设定异步数据接口的额外参数
                is_show: is_show
                // ,beginTime: beginTime
                // ,endTime: endTime
                , scopes: scopes
                , type: auth_status
                , title: title
                , id: id
                , tab_name: tab_name
                , dir: miniapp_name
                , plugin_name: plugin_name
            }, page: {curr: 1}
        });
    }

    //重置
    function reset() {

        document.getElementById("tab_name").value = '';
        // document.getElementById("beginTime").value = '';
        // document.getElementById("endTime").value = '';
        document.getElementById("id").value = '';
        document.getElementById("title").value = '';
        document.getElementById("is_show").value = '';
        document.getElementById("scopes").value = '';
        document.getElementById("miniapp_name").value = '';
        document.getElementById("plugin_name").value = '';
        //执行清空
        // $("#templateType").empty();
        form.render("select");
        //render();
        table.reload('templateList', {
            where: { //设定异步数据接口的额外参数
                is_show: null
                // ,beginTime: null
                // ,endTime: null
                , type: auth_status
                , title: null
                , id: null
                , tab_name: null
                , scopes: null
                , dir: null
                , plugin_name: null
            }, page: {curr: 1}
        });
    }

    //新增或修改

    function edit(version, id,miniapp_name) {
        if(!miniapp_name)miniapp_name = $('#miniapp_name').val();
        var currentPage = $('.layui-laypage-em').next().text();
        var title = version + "查看";
        var url = "{:Url('edit')}?id=" + id + "&app="+miniapp_name;
        var post_url = "{:Url('edit')}?app="+miniapp_name;
        if (id == 'all') {
            title = '新增';
            url = "{:Url('add')}?app="+miniapp_name;
            post_url = "{:Url('add')}?app="+miniapp_name;
        }
        layer.open({
            type: 2,
            title: title,
            shade: 0.2,
            maxmin: true,
            area: ['90%', '90%'],
            content: url,
            btn: ['立即提交'],
            yes: function (index, layero) {

                var nodeName = window["layui-layer-iframe" + index];
                var id = nodeName.getId();
                var Data = nodeName.getSaveData();
                isClick = false;
                if (Data != false) {
                    $.ajax({
                        url: post_url,
                        type: "post",
                        data: Data,
                        success: function (data) {
                            //console.log(data.status);
                            if (data.data.errcode == 0) {
                                layer.close(index);
                                layer.msg('处理中...', {shade: [0.2, '#393D49'], time: 60 * 60 * 2000});
                                layer.msg('提交成功', {
                                    icon: 6,
                                    time: 1000 //1.5秒关闭（如果不配置，默认是3秒）
                                });
                                setTimeout(function () {
                                    isClick = true;
                                    layer.close(index);
                                    if (id != null && id != '') {
                                        curr = currentPage;
                                        reload();
                                    } else {
                                        reset();
                                    }
                                }, 1500);
                            } else if (data.data.errcode != 0) {
                                layer.msg(data.msg, {
                                    icon: 5,
                                    time: 1500 //1.5秒关闭（如果不配置，默认是3秒）
                                });
                                isClick = true;
                            } else {
                                layer.msg('操作失败！请稍后再试。', {
                                    icon: 5,
                                    time: 1500 //1.5秒关闭（如果不配置，默认是3秒）
                                });
                                isClick = true;
                            }
                        }
                    });
                }
            }
        });
    }

    //新增或修改

    function addconfig(version, id, tab_id,miniapp_name) {
        if(!miniapp_name)miniapp_name = $('#miniapp_name').val();
        var currentPage = $('.layui-laypage-em').next().text();
        var title = version + "查看";
        var url = "{:Url('editconfig')}?id=" + id + "&tab_id=" + tab_id + "&app=" + miniapp_name;
        var post_url = "{:Url('editconfig')}?app="+ miniapp_name;
        if (id == 'all') {
            title = '新增';
            url = "{:Url('addconfig')}?tab_id=" + tab_id+ "&app=" + miniapp_name;
            post_url = "{:Url('addconfig')}?app="+ miniapp_name;
        }
        layer.open({
            type: 2,
            title: title,
            shade: 0.2,
            maxmin: true,
            area: ['90%', '90%'],
            content: url,
            btn: ['立即提交'],
            yes: function (index, layero) {

                var nodeName = window["layui-layer-iframe" + index];
                var id = nodeName.getId();
                var Data = nodeName.getSaveData();
                isClick = false;
                if (Data != false) {
                    $.ajax({
                        url: post_url,
                        type: "post",
                        data: Data,
                        success: function (data) {
                            console.log(data);
                            if (data.data.errcode == 0) {
                                layer.close(index);
                                layer.msg('处理中...', {shade: [0.2, '#393D49'], time: 60 * 60 * 2000});
                                layer.msg('提交成功', {
                                    icon: 6,
                                    time: 1000 //1.5秒关闭（如果不配置，默认是3秒）
                                });
                                setTimeout(function () {
                                    isClick = true;
                                    layer.close(index);
                                    if (id != null && id != '') {
                                        curr = currentPage;
                                        reload();
                                    } else {
                                        reset();
                                    }
                                }, 1500);
                            } else if (data.data.errcode != 0) {
                                layer.msg(data.msg, {
                                    icon: 5,
                                    time: 1500 //1.5秒关闭（如果不配置，默认是3秒）
                                });
                                isClick = true;
                            } else {
                                layer.msg('操作失败！请稍后再试。', {
                                    icon: 5,
                                    time: 1500 //1.5秒关闭（如果不配置，默认是3秒）
                                });
                                isClick = true;
                            }
                        }
                    });
                }
            }
        });
    }


    function getLocalTime(nS) {
        return new Date(parseInt(nS) * 1000).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
    }


    var isClick = true;

    //删除
    function del(id,miniapp_name) {
        if(!miniapp_name)miniapp_name = $('#miniapp_name').val();
        var ids = new Array();
        if (id == 'all') {
            var checkStatus = table.checkStatus('templateList');
            var data = checkStatus.data;
            if (data == 0) {
                layer.alert('请选择');
                return;
            }
            for (var i = 0; i < data.length; i++) {
                ids[i] = data[i].id;
            }
        } else {
            ids[0] = id;
        }
        if (isClick) {
            layer.confirm('真的要删除么', function (index) {
                isClick = false;
                layer.close(index);
                $.ajax({
                    url: "{:Url('softdleting')}",
                    type: "post",
                    data: {"ids": ids.toString(), 'app': miniapp_name},
                    success: function (data) {
                        layer.close(index);
                        if (data.data.errcode == 0) {
                            layer.msg('删除成功', {
                                icon: 6,
                                time: 1500 //1.5秒关闭（如果不配置，默认是3秒）
                            });
                            setTimeout(function () {
                                isClick = true;
                                reload();
                            }, 1500);
                        } else {
                            isClick = true;
                            layer.msg(data.msg, {
                                icon: 5,
                                time: 1500 //1.5秒关闭（如果不配置，默认是3秒）
                            });
                        }
                    }, error: function () {

                    }
                });
            });
        }
    }


    //显示大图片
    function show_img(t) {
        var t = $(t).find("img");
        //页面层
        layer.open({
            type: 1,
            title: '',
            //skin: 'layui-layer-rim', //加上边框
            area: ['80%', '80%'], //宽高
            shadeClose: true, //开启遮罩关闭
            end: function (index, layero) {
                return false;
            },
            content: '<div style="text-align:center"><img src="' + $(t).attr('src') + '" height="40%" width="40%" /></div>'
        });
    }

    //根据分类id获取分类名称
    function getCategoryName(id) {
        var json = '{category_json}';
        json = HTMLDecode(json);//html反转移
        var obj = JSON.parse(json);//json解析成对象
        for (let k in obj) {
            if (k == id) {
                return obj[k];
            }
        }
        return '无分类';
    }

    function HTMLDecode(text) {
        var temp = document.createElement("div");
        temp.innerHTML = text;
        var output = temp.innerText || temp.textContent;
        temp = null;
        return output;
    }

    function list(tab_name, scopes, dir, id) {
        //得到参数
        var rq = {
            'tab_id': id,
            'tab_name': tab_name,
            'scopes': scopes,
            'dir': dir,
        };
        var param = $.param(rq);
        layer.open({
            type: 2,
            title: '配置列表',
            shade: 0.2,
            maxmin: true,
            area: ['90%', '90%'],
            content: "{:Url('configindex')}?" + param,
            //btn: ['立即提交'],
            yes: function (index, layero) {


            }
        })

    }

</script>
{/block}